package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.HotKeyAdapter;
import com.jdy.haoduoaiteacher.adapter.KeyListAdapter;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.HotSearchKey;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

//import com.jdy.haoduoaiteacher.R;

/**
 * new key search
 * 
 * @author lzq
 * 
 */
public class SearchActivity extends BaseActivity implements OnClickListener,
    OnItemClickListener, TextWatcher {

  @InjectView(id = R.id.cancel, click = true)
  private ImageButton cancle;
  @InjectView(id = R.id.editbox)
  private EditText editbox;
  @InjectView(id = R.id.gridview)
  private GridView gridView;
  @InjectView(id = R.id.listview)
  private ListView listView;

  private ArrayList<HotSearchKey> mList;
  private ArrayList<String> mList1;
  private HotKeyAdapter adapter;
  private KeyListAdapter listAdapter;
  private String key = "";
  private LeUser leUser;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);
    hideTitleView();
    // hideButtomView();
    initialize();
    initListener();
    showKeyboard();
    requestHotkey();
    searchDictionary();
  }

  private void initListener() {
    listView.setOnItemClickListener(this);
    gridView.setOnItemClickListener(this);
    editbox.addTextChangedListener(this);
  }

  private String searchType;

  private void initialize() {
    mList = new ArrayList<HotSearchKey>();
    mList1 = new ArrayList<>();
    leUser = MyTeacherApp.getInstance().getUserTeacher();

    Intent it = getIntent();
    if (it != null) {
      searchType = it.getStringExtra("type");
    }
  }

  private void showKeyboard() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        InputMethodManager inputManager = (InputMethodManager) editbox
            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editbox, 0);
      }
    }, 200);
  }

  private ArrayList<String> searchHotWordsList = new ArrayList<>();

  private void searchDictionary() {
    searchHotWordsList.clear();
    new CustomAsyncTask(SearchActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
          JSONArray array;
          try {
            array = new JSONArray(result.data);
            for (int i = 0; i < array.length(); i++) {
              searchHotWordsList.add(array.optString(i).toString());
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }

          // mList = (ArrayList<HotSearchKey>) JsonSerializer.getInstance()
          // .deserialize(result.data, ArrayList.class, HotSearchKey.class);
          // setListAdapter();
          // dismissLoading();
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("catalog", searchType);

        return HttpUtils.startRequest(HttpUtils.HOST_API
            + "/api/2.0/catalog/search_dictionary", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void requestHotkey() {
    showloading("");
    new CustomAsyncTask(SearchActivity.this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          mList = (ArrayList<HotSearchKey>) JsonSerializer.getInstance()
              .deserialize(result.data, ArrayList.class, HotSearchKey.class);
          setListAdapter();
          dismissLoading();
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        // param_.put("catalog", searchType);

        return HttpUtils.startRequest(HttpUtils.HOST_API
            + HttpUtils.HOT_SEARCH_GET, param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void setListAdapter() {
    if (adapter == null) {
      adapter = new HotKeyAdapter(this, mList);
      gridView.setAdapter(adapter);
    } else {
      adapter.notifyDataSetChanged();
    }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.cancel:
      finish();
      break;

    default:
      break;
    }
  }

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    Intent intent = new Intent();
    Bundle bundle = new Bundle();
    switch (arg0.getId()) {
    case R.id.listview:
      key = mList1.get(arg2);
      listView.setVisibility(View.GONE);
      intent.setClass(this, ChoiceActivity.class);
      intent.putExtra("key", key);
      intent.putExtra("searchType", searchType);
      startActivity(intent);
      key = "";
      break;
    case R.id.gridview:
      intent.setClass(this, ChoiceActivity.class);
      bundle.putSerializable("searchkey", mList.get(arg2));
      intent.putExtra("searchType", searchType);
      intent.putExtras(bundle);
      startActivity(intent);
      break;
    default:
      break;
    }
  }

  @Override
  public void afterTextChanged(Editable arg0) {
  }

  @Override
  public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
  }

  @Override
  public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    if (TextUtils.isEmpty(key)) {
      keySearch(arg0.toString());
    }
  }

  // 根据关键字搜索
  private void keySearch(String key) {
    mList1.clear();
    if (key.length() > 0) {
      mList1.add(key);

      for (int i = 0; i < searchHotWordsList.size(); i++) {
        if (searchHotWordsList.get(i).contains(key)) {
          String strTemp = searchHotWordsList.get(i)
              .substring(1, searchHotWordsList.get(i).length() - 1).split(":")[1];
          mList1.add(strTemp.substring(1, strTemp.length() - 1));
        }
      }

    }
    if (mList1.size() > 0) {
      listView.setVisibility(View.VISIBLE);
      listAdapter = new KeyListAdapter(this, mList1, key);
      listView.setAdapter(listAdapter);
    } else {
      listView.setVisibility(View.GONE);
    }
  }

}
